package com.javaweb.oa02.user;

import com.javaweb.oa02.util.DButil;
import com.javaweb.oa02.web.action.userSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 李小玲
 * @description 登录
 */
@WebServlet({"/dept/login"})
public class login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //解决字符乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取form表单提交的username和password
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //连接数据库判断用户名密码是否正确
        Connection conn= null;
        PreparedStatement ps= null;
        ResultSet rs=null;
        boolean success=false;
        try {
            conn= DButil.getConnection();
            String sql= "select * from user where username=? and password=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs=ps.executeQuery();
            if(rs.next()){
                success=true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(conn,ps,rs);
        }

        //用户名密码正确
        if(success ){
            HttpSession session= req.getSession();
            //存userSession促发监听
            userSession user1= new userSession(username,password);
            session.setAttribute("user",user1);
            //存username，后面用来判断是否已登录，用session会话域存登录状态
            session.setAttribute("username",username);

            //选择了十天免登录，用cookies存登录状态
            if("1".equals(req.getParameter("s"))){
            Cookie cookie1= new Cookie("username",username);
            Cookie cookie2= new Cookie("password",password);
            cookie1.setMaxAge(3600*24*10);
            cookie2.setMaxAge(3600*24*10);
            //设置cookie访问路径，只要是访问这个web应用就要携带这两个cookie
            cookie1.setPath(req.getContextPath());
            cookie2.setPath(req.getContextPath());
            //将cookie响应给浏览器
            resp.addCookie(cookie1);
            resp.addCookie(cookie2);
            }
            resp.sendRedirect(""+req.getContextPath()+"/dept/list");
        }
        //用户名密码错误
        else{
            resp.sendRedirect(""+req.getContextPath()+"/error.jsp");
        }
    }
}
